package edu.maine.usm.server;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ServletConfigAware;
import org.springframework.web.servlet.ModelAndView;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Bridge class that hands off request to the Remote Service implementations
 */
@Controller
@RequestMapping("/*")
public class SpringGwtBridge implements ServletConfigAware {
	
	public SpringGwtBridge() {
		System.out.println("Instantiated");
	}

	private final Map<String, RemoteServiceServlet> services = new HashMap<String, RemoteServiceServlet>();
	
	public void setServices(Map<String, Object> servicesMap) {
		for(Entry<String, Object> entry : servicesMap.entrySet()) {
			services.put(entry.getKey(), new RemoteServiceServlet(entry.getValue()));
		}
	}

	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView handleTHIS(HttpServletRequest request, HttpServletResponse response) {
		String path = request.getRequestURI();
		
		for(Entry<String, RemoteServiceServlet> entry : services.entrySet()) {
			if (path.endsWith(entry.getKey())) {
				entry.getValue().doPost(request, response);		
				break;
			}
		}
		
		return null;
	}
	public void setServletConfig(ServletConfig servletConfig) {
		for(RemoteServiceServlet rs : services.values()) {
			try {
				rs.init(servletConfig);
			} catch (ServletException e) {
			}
		}		
	}
}
